package main

import (
	"fmt"

	appsv1 "k8s.io/api/apps/v1" // 引入 Deployment 所在的包
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {
	// 加载 Kubernetes 集群配置
	config, err := clientcmd.BuildConfigFromFlags("", "../config/config")
	if err != nil {
		panic(err.Error())
	}
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}

	// 创建 Informer 工厂
	factory := informers.NewSharedInformerFactory(clientset, 0)

	// 获取 Deployment Informer
	deploymentInformer := factory.Apps().V1().Deployments().Informer()

	// 添加事件回调函数
	deploymentInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) {
			deployment := obj.(*appsv1.Deployment)
			fmt.Printf("Deployment added: %s\n", deployment.Name)
		},
		UpdateFunc: func(oldObj, newObj interface{}) {
			oldDeployment := oldObj.(*appsv1.Deployment)
			// newDeployment := newObj.(*appsv1.Deployment)
			fmt.Printf("Deployment updated: %s\n", oldDeployment.Name)
		},
		DeleteFunc: func(obj interface{}) {
			deployment := obj.(*appsv1.Deployment)
			fmt.Printf("Deployment deleted: %s\n", deployment.Name)
		},
	})

	// 启动 Informer
	stopper := make(chan struct{})
	go factory.Start(stopper)

	// 等待 Informer 启动完成
	factory.WaitForCacheSync(stopper)

	// 阻塞主进程
	select {}
}
